
package com.mengmeizi.util;

import com.mengmeizi.net.NetWorkTool;

import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

public class DownloadManager {

    private Context context;

    /* 下载地址 */
    private String downUrl;

    /* 下载比例 */
    private int rate;

    private String pkgName;

    public DownloadManager(Context context, String downUrl, String pkgName) {
        this.context = context;
        this.downUrl = downUrl;
        this.pkgName = pkgName;
        // 启动线程下载
        downThread.start();
    }

    Thread downThread = new Thread() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            super.run();
            int response = -1;
            int readLenght = -1;
            int totalSize = -1;
            float downSize = 0;
            FileOutputStream fos = null;
            InputStream is = null;
            byte[] data = new byte[1024];
            try {
                File file = new File(pkgName);
                NetWorkTool networkTool = new NetWorkTool(context);
                networkTool.setTimeout(5000);
                networkTool.setURL(downUrl);
                HttpURLConnection httpConn = networkTool.httpConnection();
                response = httpConn.getResponseCode();
                if (response == HttpURLConnection.HTTP_OK) {
                    totalSize = httpConn.getContentLength();
                    file.createNewFile();
                    fos = new FileOutputStream(file);
                    is = httpConn.getInputStream();
                    while ((readLenght = is.read(data)) != -1 && status) {
                        downSize += readLenght;
                        fos.write(data, 0, readLenght);
                        fos.flush();
                        rate = (int) (downSize / totalSize * 100);
                    }
                }
            } catch (IOException ie) {
                ie.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
            }
        }

    };

    private boolean status = true;

    public void setStatus(boolean status) {
        this.status = status;
    }

    /***
     * 获得下载比例
     * 
     * @return
     */
    public int getDownRate() {
        return rate;
    }
}
